
from threading import Thread,Lock
from multiprocessing import Process,Lock,Queue

'''
#进程锁
def my_file(index,Lock):
    with Lock:
        with open("lesson2_test_file","a",encoding="utf-8") as f:
            f.write(str(index) + "\n")

if __name__ == "__main__":
    lock = Lock()
    f_array = []
    for i in range(12):
        p = Process(target = my_file,args=(i,lock))
        f_array.append(p)
        p.start()
    for p in f_array:
        p.join()

#线程锁
zero = 0
lock = Lock()
def foo():
    global zero
    for i in range(10**5):
        with lock:
            zero += 1
            zero -= 1

if __name__ == "__main__":
    f_array = []
    for i in range(12):
        t = Thread(target = foo)
        f_array.append(t)
        t.start()
    for t in f_array:
        t.join()

    print(zero)
'''
#多进程通过Queue来实现进程通信
def save_to_queue(index, my_queue):
    my_queue.put(index)

if __name__ == "__main__":
    f_array = []
    my_queue = Queue()
    for i in range(12):
        p = Process(target = save_to_queue,args=(i,my_queue))
        f_array.append(p)
        p.start()
    for p in f_array:
        p.join()

    while True:
        print(my_queue.get())
